{% extends "manage/layout.html" %}

{% set page_title = '教室管理' %}

{% block css %}
<style type="text/css">
    .grey{
        color: #bbb;
    }
    #createmodal .modal-body{
        margin:20px 0 10px 10%;
    }
    .classroom{
        color: red;
    }
    .system{
        color: #545454;
    }
    .course-map{
        padding-left: 150px;
    }
    .course-map .course-select{
        padding: 10px 0 0 20px;
    }
    .course-map .course-select .select-one{
        margin-bottom: 15px;
    }
    .course-map .course-select .dateup{
        margin-left: 40px;
    }
    .datetimepickers[disabled]{
        cursor: not-allowed;
        background-color: #eee;
        opacity: 1;
    }
    .datetimepickers{
        padding: 4px;
        margin-top: 1px;
        -webkit-border-radius: 4px;
        -moz-border-radius: 4px;
        border-radius: 4px;
        direction: ltr;
    }
</style>
{% endblock %}

{% block content %}
<div class="m-content">
    <div class="table-top">
        <div>
            <span>您正在管理</span>
            <select id="select_school">
                {% for school in schools %}
                    {% if selected.id == school.id %}
                    <option value="{{ school.id }}" selected>{{ school.name }}</option>
                    {% else %}
                    <option value="{{ school.id }}">{{ school.name }}</option>
                    {% endif %}
                {% endfor %}
            </select>
         </div>
        {% if current_user.has_permission('EDIT') -%}
        <button id="new" class="btn btn-default">新建</button>
        {%- endif %}
    </div>
    <table class="table table-striped table-condensed table-bordered">
        <thead>
            <tr>
                <th>教室名称</th>
                <th>教室类型</th>
                <th>教室容量</th>
                <th>创建时间</th>
                <th>教室密钥</th>
                <th>版本</th>
                <th>内容版本</th>
                {% if current_user.has_permission('EDIT') -%}
                <th>管理</th>
                {%- endif %}
            </tr>
        </thead>
        <tbody>
            {% for c in classrooms %}
            <tr id="{{ c.id }}">
                <td class="course_date" style="display: none;">{{ c.course_expire_date }}</td>
                <td class="classroom_name">{{ c.name }}</td>
                <td class="classroom_type" data-classroom_type="{{ c.classroom_type }}">{{ c.classroom_type_name }}</td>
                <td class="capacity">{{ c.capacity }}</td>
                <td class="created_at">{{ c.created_at }}</td>
                <td class="token">{{ c.token }}</td>
                <td class="system_version" data-version_type="{{ c.system_version.type }}">{{ c.system_version.value }}</td>
                <td class="contents_version">
                    {%- if c.contents_version -%}
                     <span style="color:red">{{ c.contents_version }}</span>
                    {%- else %}
                     <span class="contents_version_default">默认</span>
                    {%- endif -%}
                </td>
                {% if current_user.has_permission('EDIT') -%}
                <td>
                    <span class="glyphicon glyphicon-list-alt"></span>
                    <span class="glyphicon glyphicon-edit"></span><span class="glyphicon glyphicon-trash"></span>
                </td>
                {%- endif %}
            </tr>
            {% endfor %}
        </tbody>
    </table>
</div>

<div id="versions" class='hidden'>
    {% for version in versions %}
    <option class='package_version'>{{ version }}</option>
    {% endfor %}
    <option class='sys_version'>{{ app_version }}</option>
</div>

<div class="modal" id="createmodal">
    <div class="modal-dialog">
        <div class="modal-content">
            <button style="margin:5px 5px 0 0" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <div class="modal-body">
                <form class="form-horizontal">
                    <div class="form-group">
                        <label class="col-sm-3">教室名称：</label>
                        <div class="col-sm-6">
                            <input type="text" class="form-control" id="classroom_name">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-3">教室类型：</label>
                        <div class="col-sm-6">
                            <select class="selectpicker" id='classroom_type'>
                                <option value="1">钢琴教室</option>
                                <option value="2">尤克里里教室</option>
                                <option value="3">非洲鼓教室</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-3">教室容量：</label>
                        <div class="col-sm-6">
                            <input type="number" class="form-control" id="capacity">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-3">教室版本：</label>
                        <div class="col-sm-6">
                            <select class="selectpicker" id='version'>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-3">内容版本：</label>
                        <div class="col-sm-6">
                            <select class="selectpicker" id='contents_version'>
                                <option class='package_version' value=''>(系统默认)</option>
                                {% for version in contents_versions %}
                                <option class='package_version' value='{{ version }}'>{{ version }}</option>
                                {% endfor %}
                            </select>
                        </div>
                    </div>
                    {# 这里的功能暂时去掉，问题号：COS-683
                    <div class="form-group">
                        <label class="col-sm-3">课程权限：</label>
                        <div class="course-map">
                            <p>儿童课</p>
                            <div class="course-select">
                                <div class="select-one">
                                    <input type="checkbox" value="1" checked disabled> 地图1 <span class="grey">(永久有效) </span><br>
                                </div>
                                <div class="select-one">
                                    <input type="checkbox" name="childClass" value="2"> 地图2  <span class="dateup">到期日 <input alt="1" type="text" value="" disabled placeholder="点击选择日期" class="datetimepickers"></span>
                                </div>
                                <div class="select-one">
                                    <input type="checkbox" name="childClass" value="3"> 地图3  <span class="dateup">到期日 <input alt="2" type="text" value="" disabled  placeholder="点击选择日期" class="datetimepickers"></span><br>
                                </div>
                            </div>
                        </div>
                    </div>
                    #}

                    <div class="form-group">
                        <div class="col-sm-offset-4">
                            <a id="new_confirm" class="btn btn-default">确认</a>
                            <a class="btn btn-default">返回</a>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="modal" id="deletemodal">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-body">
                <p>确认删除？</p>
                <button class="btn btn-danger">确认</button>
                <button class="btn btn-default">取消</button>
            </div>
        </div>
    </div>
</div>

{% endblock %}

{% block js%}
<script>
var classroom_id;
var operation = 'new';
var checkChild = ['2099/1/1 23:59:59','',''];

function cleanFields(){
    $('#classroom_name').val('');
    $('#classroom_type').val('1');
    $('#capacity').val('');
    $('#capacity').removeAttr('readonly');
    $('#contents_version').val('');
    $('#classroom_type').removeAttr('disabled');
    for(var i = 0; i<$('input[name="childClass"]').length;i++){
        $('input[name="childClass"]')[i].checked = false;
    }
    for(var i = 0; i<$('.datetimepickers').length;i++){
        $('.datetimepickers')[i].value = '';
        $('.datetimepickers')[i].disabled = true;
    }
    checkChild = ['2099/1/1 23:59:59','',''];
}

function get_package_versions(){
    var versions = [];
    $('#versions option.package_version').each(function(index, value){
        version = {'type': 'classroom', 'value': $(value).text()};
        versions.push(version);
    });

    // add app version
    versions.push({'type': 'system', 'value': $('#versions option.sys_version').text()});
    return versions;
}

function get_sys_version(){
    var version = {'type': 'system', 'value': $('#versions option.sys_version').text()}
    return version;
}

function createVersionOptionString(version, selected){
    var v_type = version['type'];
    var value = version['value'];
    var selectedStr = "";
    if (selected){
        selectedStr = " selected='selected' ";
    }
    var htmlStr;
    if (v_type == 'classroom'){
        htmlStr = "<option"+ selectedStr + " type='" + v_type + "' value='"+ value +"'>" + value + "</option>";
    } else {
        htmlStr = "<option"+ selectedStr + " type='" + v_type + "' value='"+ value +"'>" + value + "（系统默认版本）</option>";
    }

    return htmlStr;
}

function fillVersionOptions(version_selected){
    var versions = get_package_versions();

    var htmlStr = "";
    for (var i=0; i<versions.length; i++){
        var selected = false;
        if (versions[i]['type'] == version_selected['type'] && versions[i]['value'] == version_selected['value']){
            selected = true;
        }
        htmlStr += createVersionOptionString(versions[i], selected);
    }

    $('#createmodal select#version').html(htmlStr);
}

$(function(){
    // COS-683
    // $('input[name="childClass"]').change(function(){//儿童课选择触发事件
    //     var checkedArr = $('input[name="childClass"]:checked');
    //     if(this.checked){
    //         $(this).parent().find('.datetimepickers').removeAttr('disabled');
    //     }else{
    //         $(this).parent().find('.datetimepickers').attr('disabled','true');
    //         $(this).parent().find('.datetimepickers').val('');
    //         checkChild[this.value-1] = '';
    //     }
    // });

    $('.datetimepickers').change(function(){
        checkChild[this.alt] = this.value + ' 23:59:59';
    })

    $('.datetimepickers').datetimepicker({//时间选择器配置
        format: 'yyyy/mm/dd',
        autoclose: true,
        minView: '2',
        bootcssVer: 3,
        language:'zh-CN'
    });

    $('#classroom_type').change(function(){
        var type = $(this).val();
        if(type == '1'){
            $('#capacity').removeAttr('readonly');
        } else {
            $('#capacity').val('0');
            $('#capacity').attr('readonly', 'readonly');
        }
    });


    $('.glyphicon-list-alt').bind('click', function(){
        var cid = $(this).parent().parent().attr('id');
        window.location.href = '/manage/classrooms/' + cid +'/devices';
    });

    $('.glyphicon-trash').bind('click',function(){
        $('#deletemodal').modal('show');
        classroom_id = $(this).parent().parent().attr('id');
        operation = 'new';
    });

    $('.glyphicon-edit').bind('click',function(){
        cleanFields();
        operation = 'edit';
        var $tr = $(this).parent().parent();
        // var course_date = $tr.find('.course_date').text()!=='' ? JSON.parse($tr.find('.course_date').text()) : '';//COS-683
        var name = $tr.find('.classroom_name').text();
        var classroom_type = $tr.find('.classroom_type').data('classroom_type');
        var capacity = $tr.find('.capacity').text();
        var version_value = $tr.find('.system_version').text();
        var version_type = $tr.find('.system_version').data('version_type');
        var version = {'type': version_type, 'value': version_value}
        var contents_version = $tr.find('.contents_version').text();
        if($tr.find('.contents_version').children('span').hasClass('contents_version_default')){
            $('#contents_version').val('');
        }else{
            $("#contents_version").val(contents_version);
        }
        classroom_id = $tr.attr('id');

        if (classroom_type == '2') {
            $('#capacity').attr('readonly', 'readonly');
        }
        // COS-683
        // if(course_date!==''){
        //     for(var i in course_date){
        //         if(i == 'course_children'){
        //             for(var j in course_date[i]){
        //                 if(j>1){
        //                     for(var k = 0; k < $('input[name="childClass"]').length; k++){
        //                         if(j == $('input[name="childClass"]')[k].value){
        //                             $('input[name="childClass"]')[k].checked=true;
        //                             $($('input[name="childClass"]')[k]).parent().find('.datetimepickers').removeAttr('disabled');
        //                             $($('input[name="childClass"]')[k]).parent().find('.datetimepickers').val(course_date[i][j]);
        //                             checkChild[k+1] = course_date[i][j] + ' 23:59:59';
        //                         }
        //                     }
        //                 }
        //             }
        //         }
        //     }
        // }

        $('#classroom_type').attr('disabled', 'disabled');

        $('#classroom_name').val(name);
        $('#classroom_type').val(classroom_type);
        $('#capacity').val(capacity);

        fillVersionOptions(version);
        $('#createmodal').modal('show');

    });

    $('#deletemodal button.btn-danger').bind('click', function(){
        var url = '/manage/classrooms/delete/' + classroom_id;
        $.post(url, function(data){
            if (data['code'] != 0){
                kalert(data['msg']);
                return;
            }
            location.reload();
        }, 'json');
    });

    $('#deletemodal button').bind('click', function(){
        $('#deletemodal').modal('hide');
    });

    $('#select_school').bind('change', function(){
        var school_id = $('#select_school option:selected').val();
        var url = '/manage/schools/' + school_id + '/classrooms'
        window.location.href = url;
    });

    $('#createmodal a').click(function(){
        $('#createmodal').modal('hide');
    })

    $('#new').click(function(){
        operation = 'new';
        cleanFields();
        fillVersionOptions(get_sys_version());
        $('#createmodal').modal('show');
    })

    $('#new_confirm').click(function(){
        var classroom_name = $('#classroom_name').val();
        var classroom_type = $('#classroom_type').val();
        var capacity = $('#capacity').val();
        var version = $('#version option:selected').val();
        var version_type = $('#version option:selected').attr('type');
        var contents_version = $('#contents_version option:selected').val();
        var checkedArr = $('input[name="childClass"]:checked');
        var date = $('.datetimepickers');

        if(checkedArr.length!=0){
            for(var i = 0; i < checkedArr.length; i++){
                if($(checkedArr[i]).parent().find('.datetimepickers')[0].value == ''){
                    kalert('必须设定课程到期日');
                    return;
                }else{
                    var tod = new Date();
                    var thd = new Date($(checkedArr[i]).parent().find('.datetimepickers')[0].value);
                    if(thd.getTime()<tod.getTime()){
                        kalert('不允许选择今天及以前的日期');
                        return;
                    }
                }
            }
        }

        if (classroom_name.length > 20 || classroom_name.length < 1){
            kalert('教室名称不符合条件');
            return;
        }
        if (classroom_type == '1' && (isNaN(capacity) || capacity < 1)){
            kalert('必须是大于0的整数');
            return;
        }

        var school_id = $('#select_school option:selected').val();
        var url, data={};
        if (operation == 'new'){
            url = '/manage/classrooms/new';
            data = {
                'name': classroom_name,
                'classroom_type': classroom_type,
                'capacity': capacity,
                'school_id': school_id,
                'version': version,
                'version_type': version_type,
                'contents_version': contents_version,
                'course_children': checkChild.join(',')
            };
        }
        else if (operation == 'edit'){
            url = '/manage/classrooms/edit/' + classroom_id;
            data = {
                'name': classroom_name,
                'classroom_type': classroom_type,
                'capacity': capacity,
                'version': version,
                'version_type': version_type,
                'contents_version': contents_version,
                'course_children': checkChild.join(',')
            };
        }

    $.post(url, data, function(data){
        if (data['code']!=0){
            kalert(data['msg']);
            cleanFields();
            return;
        }
        location.reload();
    }, 'json');
    });


});
</script>
{% endblock %}
